package com.esm.sm800.sm800floating;

import com.esm.sm800.R;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFPicture;
import org.apache.poi.hssf.usermodel.HSSFPictureData;
import org.apache.poi.hssf.usermodel.HSSFShape;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Iterator;

import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableImage;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

public class browser_dz_report extends Activity implements View.OnClickListener {

    private String usbRootPath = "";    // u盘存储目录
    private String usbESMPath = "";     // U盘的ESM工作目录

    private TextView editText_startdate, editText_enddate;
    Button ckbb_report_btsearch, ckbb_report_export, ckbb_report_return;
    TableLayout tableLayout;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 设置Activity为全屏
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_browser_dz_report);

        // 获取传递过来的Intent对象的参数
        Intent intent = getIntent(); // 获取传递过来的Intent对象
        usbRootPath = intent.getStringExtra("usbRootPath"); // 获取参数值
        usbESMPath = intent.getStringExtra("usbESMPath"); // 获取参数值

        editText_startdate = findViewById(R.id.ckbb_report_start_time);
        findViewById(R.id.ckbb_report_start_time).setOnClickListener(this);
        editText_enddate = findViewById(R.id.ckbb_report_end_time);
        findViewById(R.id.ckbb_report_end_time).setOnClickListener(this);

        ckbb_report_btsearch = findViewById(R.id.ckbb_report_btsearch);
        findViewById(R.id.ckbb_report_btsearch).setOnClickListener(this);
        ckbb_report_export = findViewById(R.id.ckbb_report_export);
        findViewById(R.id.ckbb_report_export).setOnClickListener(this);
        ckbb_report_return = findViewById(R.id.ckbb_report_return);
        findViewById(R.id.ckbb_report_return).setOnClickListener(this);

        ckbb_report_return.requestFocus();

        tableLayout=findViewById(R.id.tableLayout);

        // 读取u盘目录下needle中的断针表（领取报表）
        processExcel();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ckbb_report_start_time:
                showDatePickerDialog(1);
                break;
            case R.id.ckbb_report_end_time:
                showDatePickerDialog(2);
                break;
            case R.id.ckbb_report_btsearch:
                //this.finish();
                break;
            case R.id.ckbb_report_export:
                try {
                    exportExcel();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (BiffException e) {
                    e.printStackTrace();
                } catch (WriteException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.ckbb_report_return:
                this.finish();
                break;
        }
    }

    // 选择日期
    private void showDatePickerDialog(int k) {
        DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                // 在这里处理日期选择结果，例如更新EditText的文本
                String selectedDate = String.format("%04d-%02d-%02d", year, month + 1, dayOfMonth);
                if(k==1)
                    editText_startdate.setText(selectedDate);
                else
                    editText_enddate.setText(selectedDate);
            }
        }, Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH), Calendar.getInstance().get(Calendar.DAY_OF_MONTH));

        datePickerDialog.show();
    }

    // 读取u盘目录下needle中的断针表（领取报表）
    private void processExcel()
    {
        String needleDirectoryPath = usbRootPath + File.separatorChar + "needle";   // 在U盘上，needle目录
        String prefix = getString(R.string.ckbb_report_name_dz);
        File latestReportFile = getLatestReportFile(needleDirectoryPath, prefix);

        if (latestReportFile != null) {
            // 处理找到的最新文件
            try (FileInputStream fis = new FileInputStream(latestReportFile)) {
                Workbook workbook = WorkbookFactory.create(fis);
                Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表

                HSSFPatriarch drawing = (HSSFPatriarch) sheet.getDrawingPatriarch();
                Iterator<HSSFShape> iterator = null;
                if (drawing != null) {
                    iterator = drawing.iterator();
                }

                // 获取列表的列宽数值数组资源
                TypedArray numbersArray = getResources().obtainTypedArray(R.array.dz_report_numbers_value);

                // 获取屏幕的 DisplayMetrics
                DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
                // 将 dp 值转换为像素值
                int heightInPixels = (int) (120 * displayMetrics.density);

                 // 遍历行和列
                int iCurrentRowNum = 0;     // 当前execl的行号
                for (Row row : sheet) {
                    if(row.getRowNum() == 0) {
                        continue;
                    }

                    // 过滤代码，从excel表格里，只保留借针记录
                    int columnIndex = 13; // 要获取的列索引，从0开始，第13列是：机针状态
                    Cell mycell = row.getCell(columnIndex);
                    if (mycell != null) {
                        String cellValue = mycell.toString();
                        // 在这里进行判断，例如判断值是否为空
                        if (!cellValue.isEmpty()) {
                            //System.out.println("单元格值：" + cellValue);
                            // 判定是不是"未还“，只取"未还"的行
                            if(!cellValue.contains(getString(R.string.ckbb_report_filter_dz)))
                            {
                                continue;
                            }
                        } else {
                            System.out.println("单元格为空");
                            continue;
                        }
                    }
                    iCurrentRowNum++;

                    TableRow tableRow = new TableRow(this);

                    // 设置TextView的布局参数
                    TableRow.LayoutParams layoutParamsXH = new TableRow.LayoutParams(
                            TableRow.LayoutParams.MATCH_PARENT); // 高度

                    // 处理图片单元格
                    int iCurrentCol = 0;
                    for (Cell cell : row) {
                        if(iCurrentCol >= 16)   // 第16列和第17列（从0开始）就是：16机针照片，17员工照片
                        {
                            //HSSFPatriarch drawing = (HSSFPatriarch) sheet.getDrawingPatriarch();
                            if (drawing != null) {
                                //Iterator<HSSFShape> iterator = drawing.iterator();
                                while (iterator != null && iterator.hasNext()) {
                                    HSSFShape shape = iterator.next();
                                    if (shape instanceof HSSFShape) {
                                        if (shape instanceof HSSFPicture) {
                                            HSSFPicture picture = (HSSFPicture) shape;

                                            // 获取图片的二进制数据
                                            byte[] pictureData = ((HSSFPictureData) picture.getPictureData()).getData();

                                            // 将二进制数据解码为 Bitmap
                                            Bitmap bitmap = BitmapFactory.decodeByteArray(pictureData, 0, pictureData.length);

                                            // 如果解码成功，bitmap 将不为 null
                                            if (bitmap != null) {
                                                // 现在您可以将 bitmap 设置为 ImageView 的图片
                                                ImageView imageView = new ImageView(tableLayout.getContext()); // 确保有合适的上下文
                                                imageView.setImageBitmap(bitmap);

                                                // 创建一个TableRow.LayoutParams对象，设置宽度和高度
                                                // 187是宽度，120为图片高度，可以根据需要调整
                                                TableRow.LayoutParams layoutParamsPIC = new TableRow.LayoutParams(187, 120);
                                                // 将LayoutParams对象设置为ImageView的布局参数
                                                imageView.setLayoutParams(layoutParamsPIC);

                                                // 将 ImageView 添加到 TableRow 或其他视图容器中
                                                tableRow.addView(imageView);

                                                iCurrentCol++;

                                                if(iCurrentCol > 17)
                                                    break;

                                                continue;
                                                //break;
                                            } else {
                                                // 解码失败，处理错误情况
                                                // ...
                                            }
                                        }
                                    }
                                }
                            }
                            break;
                        }


                        // 依次追加到列表的每一列
                        TextView textView = new TextView(this);
                        textView.setText(cell.toString());

                        // 设置TextView的布局参数
                        TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(
                                TableRow.LayoutParams.MATCH_PARENT, // 宽度
                                TableRow.LayoutParams.MATCH_PARENT); // 高度
                        textView.setLayoutParams(layoutParams);
                        textView.setGravity(Gravity.CENTER);

                        // 设置表格里行高，120dp
                        // 设置 TextView 的高度
                        textView.getLayoutParams().height = heightInPixels;
                        // 设置 TextView 的宽度
                        float colWidthWeight = numbersArray.getFloat(iCurrentCol, 1); // 第二个参数是默认值，如果数组中没有元素，则返回-1
                        textView.setWidth((int)colWidthWeight);

                        // 设置单元格边框
                        textView.setBackgroundResource(R.drawable.table_layout_border);

                        tableRow.addView(textView);

                        iCurrentCol++;
                    }

                    // 追加到列表的一行中
                    tableLayout.addView(tableRow);
                    break;
                }
                // 显示总条数
                TextView ckbb_report_total = findViewById(R.id.ckbb_report_total);
                ckbb_report_total.setText(String.valueOf(iCurrentRowNum));
                // 使用完数值数组后，需要调用recycle()方法释放资源
                numbersArray.recycle();
                // 关闭excel表
                workbook.close();
            } catch (IOException | InvalidFormatException e) {
                e.printStackTrace();
            }
        } else {
            // 没有找到符合条件的文件
            Toast.makeText(this, getString(R.string.ckbb_insert_U), Toast.LENGTH_SHORT).show();
        }
    }

    @TargetApi(Build.VERSION_CODES.N)
    private File getLatestReportFile(String directoryPath, String prefix) {
        File directory = new File("", directoryPath);
        File[] files = directory.listFiles((dir, name) -> name.startsWith(prefix));
        if (files == null || files.length == 0) {
            // 没有找到符合条件的文件
            Toast.makeText(this, getString(R.string.ckbb_err_nobasicdata), Toast.LENGTH_SHORT).show();
            return null;
        }

        // 按照最后修改时间降序排序
        Arrays.sort(files, new Comparator<File>() {
            @Override
            public int compare(File file1, File file2) {
                return Long.compare(file2.lastModified(), file1.lastModified());
            }
        });

        // 输出最新文件的名称
        //System.out.println("最新的文件是：" + files[0].getName());
        return files[0];
    }

    private void exportExcel() throws IOException, WriteException, BiffException {
        int rowCount = tableLayout.getChildCount();
        if (rowCount == 0) {
            return; // 如果TableLayout是空的，直接返回
        }

        writeJXLExcel();
    }

    public void writeJXLExcel() throws IOException, WriteException {
        String filePathName = usbESMPath+ File.separatorChar + getString(R.string.ckbb_dz_title) + GlobalUtil.getCurrentDate() + ".xls";
        FileOutputStream output = new FileOutputStream(filePathName);
        try {
            WritableWorkbook wwb = jxl.Workbook.createWorkbook(output);
            WritableSheet sheet = wwb.createSheet("data", 0);

            // 格式
            WritableFont font = new WritableFont(WritableFont.createFont("宋体"),
                    8, WritableFont.NO_BOLD);// 字体样式
            WritableCellFormat wcf = new WritableCellFormat(font);
            wcf.setAlignment(jxl.format.Alignment.CENTRE);//平行居中
            wcf.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE); //垂直居中
            wcf.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN, jxl.format.Colour.BLACK); //BorderLineStyle边框

            // 第一行的行高
            sheet.setRowView(0, 500);
            // 序号
            sheet.addCell(new Label(0, 0, getString(R.string.ckbb_report_sheet_xh),wcf));
            sheet.setColumnView(0, 10);
            // 姓名
            sheet.addCell(new Label(1, 0, getString(R.string.ckbb_report_sheet_xm),wcf));
            sheet.setColumnView(1, 15);
            // 时间
            sheet.addCell(new Label(2, 0, getString(R.string.ckbb_report_sheet_sj),wcf));
            sheet.setColumnView(2, 30);
            // 组号
            sheet.addCell(new Label(3, 0, getString(R.string.ckbb_report_sheet_zh),wcf));
            sheet.setColumnView(3, 15);
            // 款号
            sheet.addCell(new Label(4, 0, getString(R.string.ckbb_report_sheet_kh),wcf));
            sheet.setColumnView(4, 15);
            // 工序
            sheet.addCell(new Label(5, 0, getString(R.string.ckbb_report_sheet_gx),wcf));
            sheet.setColumnView(5, 15);
            // 颜色
            sheet.addCell(new Label(6, 0, getString(R.string.ckbb_report_sheet_ys),wcf));
            sheet.setColumnView(6, 15);
            // 尺码
            sheet.addCell(new Label(7, 0, getString(R.string.ckbb_report_sheet_cm),wcf));
            sheet.setColumnView(7, 15);
            // 批号
            sheet.addCell(new Label(8, 0, getString(R.string.ckbb_report_sheet_ph),wcf));
            sheet.setColumnView(8, 15);
            // 机针型号
            sheet.addCell(new Label(9, 0, getString(R.string.ckbb_report_sheet_jzxh),wcf));
            sheet.setColumnView(9, 15);
            // 完整度
            sheet.addCell(new Label(10, 0, getString(R.string.ckbb_report_sheet_wzd),wcf));
            sheet.setColumnView(10, 15);
            // 通过人
            sheet.addCell(new Label(11, 0, getString(R.string.ckbb_report_sheet_tgr),wcf));
            sheet.setColumnView(11, 15);
            // 机台编号
            sheet.addCell(new Label(12, 0, getString(R.string.ckbb_report_sheet_jtbh),wcf));
            sheet.setColumnView(12, 15);
            // 机针状态
            sheet.addCell(new Label(13, 0, getString(R.string.ckbb_report_sheet_jzzt),wcf));
            sheet.setColumnView(13, 15);
            // 断针说明
            sheet.addCell(new Label(14, 0, getString(R.string.ckbb_report_sheet_dzsm),wcf));
            sheet.setColumnView(14, 15);
            // 处理方法
            sheet.addCell(new Label(15, 0, getString(R.string.ckbb_report_sheet_clff),wcf));
            sheet.setColumnView(15, 30);
            // 机针照片
            sheet.addCell(new Label(16, 0, getString(R.string.ckbb_report_sheet_jzzp),wcf));
            sheet.setColumnView(16, 30);
            // 员工照片
            sheet.addCell(new Label(17, 0, getString(R.string.ckbb_report_sheet_ygzp),wcf));
            sheet.setColumnView(17, 30);

            for (int i = 1; i < tableLayout.getChildCount(); i++) {
                TableRow row = (TableRow) tableLayout.getChildAt(i);
                sheet.setRowView(i, 2000);  // 设置行高
                for (int j = 0; j < row.getChildCount(); j++) {
                    View childView = row.getChildAt(j);
                    if (childView instanceof TextView) {
                        String text = ((TextView) childView).getText().toString();
                        sheet.addCell(new Label(j, i, text, wcf));
                    }
                    else if(childView instanceof ImageView)
                    {
                        // 获取最后一列的图片
                        ImageView imageView = (ImageView) childView;
                        Drawable drawable = imageView.getDrawable();
                        // 返回图片的字节数组
                        byte[] imageData = drawableToByteArray(drawable);
                        WritableImage image = new WritableImage(j, i, 1, 1, imageData);
                        sheet.addImage(image);
                    }
                }
            }
            output.flush();
            wwb.write(); //写入数据
            wwb.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                output.close();
                uploadFTP();
                Toast.makeText(this, getString(R.string.ckbb_export_finish), Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static byte[] drawableToByteArray(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            return stream.toByteArray();
        }
        return null;
    }

    // 上传到FTP服务器
    private void uploadFTP()
    {
        String SourcefileFullPathName = usbESMPath + File.separatorChar + getString(R.string.ckbb_dz_title) + GlobalUtil.getCurrentDate() + ".xls";
        File file = new File(SourcefileFullPathName);
        if (!file.exists())
        {
            return;
        }
        String currentLanguage = GlobalUtil.getCurrentLanguage(this);
        String DestFTPfileName = currentLanguage + "-broken-" + GlobalUtil.getCurrentDate() + ".xls";

        if(GlobalUtil.ishasdataupload_swtich) startFtpUpload(SourcefileFullPathName, DestFTPfileName);
    }

    private void startFtpUpload(String SourcefileFullPathName, String DestFTPfileName) {
        new Thread(() -> {
            GlobalUtil.getFTPLogin(getApplicationContext());
            if(GlobalUtil.Key_ftpserverip_value.isEmpty() ||
                    GlobalUtil.Key_ftpserveruser_value.isEmpty() ||
                    GlobalUtil.Key_ftpserverpass_value.isEmpty())
            {
                return;
            }
            // 在这里执行FTP上传操作
            new FtpUploadUtil(GlobalUtil.Key_ftpserverip_value, GlobalUtil.Key_ftpserveruser_value, GlobalUtil.Key_ftpserverpass_value, SourcefileFullPathName, DestFTPfileName, false).execute();
        }).start();
    }
}